package com.example.btcontroller;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import java.util.UUID;
//1573--------------------
/*import java.io.UnsupportedEncodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.net.URLDecoder;
*/
import android.widget.ListView;
import android.widget.AdapterView;
//1573--------------------
//https://www.cnblogs.com/zhangyinhua/p/7689974.html 字符串讲解
//参考网端 内：GBK:c4da,unicode 5185->utf-8 e5 86 85
//http://www.360doc.com/content/20/0330/23/277688_902764992.shtml
//http://tool.chinaz.com/tools/urlencode.aspx
//http://mytju.com/classcode/tools/encode_gb2312.asp
// https://www.cnblogs.com/xijin-wu/p/5884822.html
//https://www.cnblogs.com/s-y-j/p/6548032.html list view例

class CSB_PAR{

    public  int startstop_f = 0; //16bit

    public  int data_dis_activity = 0; //16bit
    public  int update_reg_f = 0;//0 update not ,1 update r,采集值 ,2 update rw 配置值


    public  float ws_0 = 0;
    public  float ws_1 = 0;
    public  float ws_10 = 0;
    public  float ws_30 = 0;

    public  int wd_0 = 0;
    public  int wd_1 = 0;
    public  int wd_10 = 0;
    public  int wd_30 = 0;

    public  float a_b_dis = 0;
    public  float b_a_dis = 0;
    public  float a_temp = 0;
    public  float b_temp = 0;

    public  float a_dis = 0;
    public  float b_dis = 0;

    public  int a_ft = 0;
    public  int b_ft = 0;

    public  float a_res = 0;
    public  float b_res = 0;

//下面参数区
    public  float a_b_dis_bias = 0;
    public  float a_b_l_par = 0;

    public  float a_temp_bias = 0;
    public  float b_temp_bias = 0;

    public  float a_dis_bias = 0;
    public  float b_dis_bias = 0;

    public  float AV_k = 0;
    public float section_area = 0;

}

public class MainActivity extends AppCompatActivity {

    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //获取蓝牙实例

    public static final char modbus_read = 0x03;

    public static CSB_PAR uCSB_PAR;


////////////////////////////////////////////////
    private TextView wd_0_TextView;
    private TextView wd_1_TextView;
    private TextView wd_10_TextView;
    private TextView wd_30_TextView;


    private TextView ws_0_TextView;
    private TextView ws_1_TextView;
    private TextView ws_10_TextView;
    private TextView ws_30_TextView;

    private TextView a_b_dis_TextView;
    private TextView b_a_dis_TextView;
    private TextView a_temp_TextView;
    private TextView b_temp_TextView;

    private TextView a_b_tof_TextView;
    private TextView b_a_tof_TextView;
    private TextView a_res_value_TextView;
    private TextView b_res_value_TextView;

//////////////////////////////////////////////

    /*1573*/
    private static int rx_count_time = 0;//收到数据统计
    public static String mBlue_Rx_Buffer = ""; //显示用数据缓存

    BluetoothDevice mBluetoothDevice = null; //蓝牙设备
    static BluetoothSocket mBluetoothSocket = null; //蓝牙通信Socket

    boolean bRun = true; //运行状态
    boolean time_Run_f = true; //运行状态
    boolean bThread = false; //读取线程状态
    boolean time_Thread_f = false; //读取线程状态

    private InputStream is;    //输入流，用来接收蓝牙数据

//-------------------------- 自写义函数------------------------------------

    public  void  blu_send_Str(String mStr)
    {
        int n = 0;
        if (mBluetoothSocket == null) {
            //Toast.makeText(getApplicationContext(), "请先连接设备", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            OutputStream os = mBluetoothSocket.getOutputStream();   //蓝牙连接输出流
            byte[] bos = mStr.toString().getBytes();//
            for (int i = 0; i < bos.length; i++) {
                if (bos[i] == 0x0a) n++;
            }
            byte[] bos_new = new byte[bos.length + n];
            n = 0;
            for (int i = 0; i < bos.length; i++) { //手机中换行为0a,将其改为0d 0a后再发送
                if (bos[i] == 0x0a) {
                    bos_new[n] = 0x0d;
                    n++;
                    bos_new[n] = 0x0a;
                } else {
                    bos_new[n] = bos[i];
                }
                n++;
            }
            os.write(bos_new);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 浮点转换为字节
     *
     * @param f
     * @return
     */
    public static byte[] float2byte(float f) {

        // 把float转换为byte[]
        int fbit = Float.floatToIntBits(f);

        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (fbit >> (24 - i * 8));
        }

        return b;

    }
//-------------------------- 自写义函数------------------------------------

    public  static void  blu_send_hex(byte[] bArray)
    {
        int n = 0;
        if (mBluetoothSocket == null) {
            //Toast.makeText(getApplicationContext(), "请先连接设备", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            OutputStream os = mBluetoothSocket.getOutputStream();   //蓝牙连接输出流
           // byte[] bos = bArray.length;//
           /* for (int i = 0; i < byte.length; i++) {
                if (bos[i] == 0x0a) n++;
            }
            byte[] bos_new = new byte[bos.length + n];
            n = 0;
            for (int i = 0; i < bos.length; i++) { //手机中换行为0a,将其改为0d 0a后再发送
                if (bos[i] == 0x0a) {
                    bos_new[n] = 0x0d;
                    n++;
                    bos_new[n] = 0x0a;
                } else {
                    bos_new[n] = bos[i];
                }
                n++;
            }*/
            os.write(bArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//-------------------------------------------------------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取控件ID


        //1573
        // 设置已配队设备列表

        uCSB_PAR = new CSB_PAR();

        wd_0_TextView = (TextView) findViewById(R.id.wd0_TextView);
        wd_1_TextView = (TextView) findViewById(R.id.wd1_TextView);
        wd_10_TextView = (TextView) findViewById(R.id.wd10_TextView);
        wd_30_TextView = (TextView) findViewById(R.id.wd30_TextView);


        ws_0_TextView = (TextView) findViewById(R.id.ws_0_TextView);
        ws_1_TextView = (TextView) findViewById(R.id.ws_1_TextView);
        ws_10_TextView = (TextView) findViewById(R.id.ws_10_TextView);
        ws_30_TextView = (TextView) findViewById(R.id.ws_30_TextView);

        a_b_dis_TextView = (TextView) findViewById(R.id.a_b_dis_TextView);
        b_a_dis_TextView = (TextView) findViewById(R.id.b_a_dis_TextView);
        a_temp_TextView = (TextView) findViewById(R.id.a_temp_TextView);
        b_temp_TextView = (TextView) findViewById(R.id.b_temp_TextView);
        a_b_tof_TextView = (TextView) findViewById(R.id.a_b_tof_TextView);
        b_a_tof_TextView = (TextView) findViewById(R.id.b_a_tof_TextView);
        a_res_value_TextView = (TextView) findViewById(R.id.a_res_value_TextView);
        b_res_value_TextView = (TextView) findViewById(R.id.b_res_value_TextView);


        //1573

        //如果打不开蓝牙提示信息，结束程序
        if (mBluetoothAdapter == null){
            Toast.makeText(getApplicationContext(),"无法打开手机蓝牙，请确认手机是否有蓝牙功能！",Toast.LENGTH_SHORT).show();
            finish();
            return;
        }


        //连接按钮响应
        //连接按钮响应
        final Button ble_connect_Button = findViewById(R.id.ble_connect_Button);
        ble_connect_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mBluetoothAdapter.isEnabled() == false) {
                    Toast.makeText(getApplicationContext(), " 请先打开蓝牙", Toast.LENGTH_LONG).show();
                    return;
                }

                //如果未连接设备则打开DevicesListActivity搜索设备
                if (mBluetoothSocket == null) {
                    Intent serveIntent = new Intent(getApplicationContext(), DevicesListActivity.class); //跳转活动
                    startActivityForResult(serveIntent, 1); //设置返回宏定义
                } else {
                    //关闭连接socket
                    try {
                        bRun = false;
                        Thread.sleep(2000);
                        is.close();
                        mBluetoothSocket.close();
                        mBluetoothSocket = null;
                        ble_connect_Button.setText("连接");
                        uCSB_PAR.startstop_f = 0;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        });


        //参数配置
        final Button config_par_Button = findViewById(R.id.config_par_Button);
        config_par_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mBluetoothSocket == null) {
                    Toast.makeText(getApplicationContext(), " 请先联接蓝牙", Toast.LENGTH_LONG).show();
                    return;
                }
                uCSB_PAR.startstop_f = 0;
                //send ff 03 41 1f 00 10 74 22
                //ret  FF 03 20 40 9F AE 14 40 9C CC CC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3F 80 00 00 45 BE
                byte[] bArray = new byte[8];
                bArray[0] = (byte)0xff;
                bArray[1] = (byte)modbus_read;
                bArray[2] = 0x41;
                bArray[3] = 0x1f;
                bArray[4] = 0x00;
                bArray[5] = 0x10;//size  16/4=4个数据 一个数据4个字节
                bArray[6] = 0x74;
                bArray[7] = 0x22;
                blu_send_hex(bArray);

            }
        });

        //数据显示
        final Button data_dis_Button = findViewById(R.id.data_dis_Button);
        data_dis_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mBluetoothSocket == null) {
                    Toast.makeText(getApplicationContext(), " 请先联接蓝牙", Toast.LENGTH_LONG).show();
                    return;
                }
                Toast.makeText(getApplicationContext(), " 功能未完善", Toast.LENGTH_LONG).show();
                //uCSB_PAR.data_dis_activity = 1;
                //Intent serveIntent = new Intent(getApplicationContext(), data_dis_activity.class); //跳转活动
                //startActivityForResult(serveIntent, 1); //设置返回宏定义

            }
        });


        // 设置设备可以被搜索
        new Thread(){
            public void run(){
                if(mBluetoothAdapter.isEnabled()==false){
                    mBluetoothAdapter.enable();
                }
            }
        }.start();
    }

    //接收活动结果，响应startActivityForResult()
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:     //连接结果，由DeviceListActivity设置返回
                // 响应返回结果
                if (resultCode == Activity.RESULT_OK) {   //连接成功，由DeviceListActivity设置返回
                    // MAC地址，由DeviceListActivity设置返回
                    String address = data.getExtras().getString(DevicesListActivity.EXTRA_DEVICE_ADDRESS);
                    // 得到蓝牙设备句柄
                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(address);

                    // 用服务号得到socket
                    try {
                        mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
                    } catch (IOException e) {
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    //连接socket
                    Button ble_connect_Button = findViewById(R.id.ble_connect_Button);
                    try {
                        mBluetoothSocket.connect();
                        Toast.makeText(this, "连接" + mBluetoothDevice.getName() + "成功！", Toast.LENGTH_SHORT).show();
                        ble_connect_Button.setText("断开");
                        uCSB_PAR.startstop_f = 1;
                    } catch (IOException e) {
                        try {
                            Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                            mBluetoothSocket.close();
                            mBluetoothSocket = null;
                        } catch (IOException ee) {
                            Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }

                        return;
                    }

                    //打开接收线程
                    try {
                        is = mBluetoothSocket.getInputStream();   //得到蓝牙数据输入流
                    } catch (IOException e) {
                        Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (time_Thread_f == false) {
                        timeThread.start();
                        time_Thread_f = true;
                    } else {
                        time_Run_f = true;
                    }

                    if (bThread == false) {
                        readThread.start();
                        bThread = true;
                    } else {
                        bRun = true;
                    }
                }
                break;
            default:
                break;
        }
    }

    Thread timeThread=new Thread(){
        public void run() {
            int num = 0;
            //time_Run_f = true;
            //接收线程
            while (true) {
                //发送显示消息，进行显示刷新
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                seekbar_handler.sendMessage(seekbar_handler.obtainMessage());
            }
        }
    };
    final protected static char[] hexArray ="0123456789ABCDEF".toCharArray();
    /**
     * 将字节数组转换成16进制字符串
     * @param bytes
     * @return
     */
    public static String bytes2BinaryStr(byte[] bytes){
        StringBuffer binaryStr = new StringBuffer();
        for(int i=0;i<bytes.length;i++){
            String str = Integer.toBinaryString((bytes[i] & 0xFF) + 0x100).substring(1);
            binaryStr.append(str);
        }
        return binaryStr.toString();
    }
    /**
     * Create by 郭文梁 2019/6/25 0025 10:32
     * CRC16
     * CRC16工具类
     *
     * @author 郭文梁
     * @data 2019/6/25 0025
     */
    public static class CRC {
        /**
         * 一个字节包含位的数量 8
         */
        private static final int BITS_OF_BYTE = 8;
        /**
         * 多项式
         */
        private static final int POLYNOMIAL = 0xA001;
        /**
         * 初始值
         */
        private static final int INITIAL_VALUE = 0xFFFF;

        /**
         * CRC16 编码
         *
         * @param bytes 编码内容
         * @return 编码结果
         */
        public static int crc16(byte[] bytes,int num) {
            int res = INITIAL_VALUE;
            int data;
            for (int j = 0; j < num;j++) {
                data = bytes[j];
                data = data&0xff;
                res = res ^ data;
                for (int i = 0; i < BITS_OF_BYTE; i++) {
                    res = (res & 0x0001) == 1 ? (res >> 1) ^ POLYNOMIAL : res >> 1;
                }
            }
            return revert(res);
        }

        /**
         * 翻转16位的高八位和低八位字节
         *
         * @param src 翻转数字
         * @return 翻转结果
         */
        private static int revert(int src) {
            int lowByte = (src & 0xFF00) >> 8;
            int highByte = (src & 0x00FF) << 8;
            return lowByte | highByte;
        }
    }

    /**
     * 字节数组转float
     * 采用IEEE 754标准
     * @param bytes
     * @return
     */
    public static float bytes2Float(byte[] bytes){
        //获取 字节数组转化成的16进制字符串
        String BinaryStr = bytes2BinaryStr(bytes);
        //符号位S
        Long s = Long.parseLong(BinaryStr.substring(0, 1));
        //指数位E
        Long e = Long.parseLong(BinaryStr.substring(1, 9),2);
        //位数M
        String M = BinaryStr.substring(9);
        float m = 0,a,b;
        for(int i=0;i<M.length();i++){
            a = Integer.valueOf(M.charAt(i)+"");
            b = (float) Math.pow(2, i+1);
            m =m + (a/b);
        }
        Float f = (float) ((Math.pow(-1, s)) * (1+m) * (Math.pow(2,(e-127))));
        return f;
    }
    //接收数据线程
    Thread readThread=new Thread(){

        public void run(){
            int num = 0;
            byte[] buffer = new byte[1024];

            bRun = true;
            //接收线程
            while(true){
                try{
                    while(is.available()==0){
                        while(bRun == false){}
                    }
                    while(true){
                        if(!bThread)return;//跳出循环
                        try{
                            Thread.sleep(100);//延时100ms 最多收96节字

                        }catch (Exception e){
                            break;
                        }
                        num = is.read(buffer);         //读入数据
                        //int y = CRC.crc16(buffer,num);
                        if(CRC.crc16(buffer,num) == 0){//收到正确数据
                            if((buffer[1] == 0x03)&&(buffer[2] == 0x20)){ //读到数据返回之配置
                                byte[] bytes = new byte[]{0x00,(byte)0x00,0x00,0x00};
                                int index = 3;
                                float f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_b_dis_bias = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_b_l_par = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.AV_k = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_temp_bias = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.b_temp_bias = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_dis_bias = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.b_dis_bias = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.section_area = f;
                                uCSB_PAR.update_reg_f = 2;//更新参数区
                            }else if((buffer[1] == 0x03)&&(buffer[2] == 0x3e)){  //读62个字节参数
                                byte[] bytes = new byte[]{0x00,(byte)0x00,0x00,0x00};
                                int index = 3;
                                float f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.ws_0 = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.ws_1 = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.ws_10 = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.ws_30 = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_b_dis = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.b_a_dis = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_dis = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.b_dis = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.a_temp = f;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++];  f = bytes2Float(bytes);uCSB_PAR.b_temp = f;
                                int tmp;
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.wd_0 = tmp; //瞬时风向
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.wd_1 = tmp;//瞬时风向//1
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.wd_10 = tmp;//瞬时风向//10
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.wd_30 = tmp;//瞬时风向//30

                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.a_ft = tmp;//飞行时间
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.b_ft = tmp;//飞行时间

                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.a_res =(float)tmp/1000;//温度电阻
                                bytes[0] = buffer[index++];bytes[1] = buffer[index++]; tmp = bytes[0];tmp<<=8;tmp+=bytes[1];uCSB_PAR.b_res = (float)tmp/1000;//温度电阻

                                bytes[0] = buffer[index++];bytes[1] = buffer[index++];bytes[2] = buffer[index++];bytes[3] = buffer[index++]; //断面风量 f = bytes2Float(bytes);uCSB_PAR.b_dis = f;


                                uCSB_PAR.update_reg_f = 1;//更新参数区
                            }//ff 10 41 1f 00 10 f1 e1
                        }else if(buffer[1] == 0x10){  //设置参数成功返回
                           // Toast.makeText(getApplicationContext(), "设定成功！", Toast.LENGTH_SHORT).show();
                        }else{
                            System.out.println("err--------crc_check!");
                        }

                        char[] hexChars = new char[num * 3 + 2];
                        int x = 0;
                        for (int j = 0; j < num; j++) {
                            int v = buffer[j] & 0xFF;
                            hexChars[x++] = hexArray[v >>> 4];
                            hexChars[x++] = hexArray[v & 0x0F];
                            hexChars[x++] = ' ';
                        }
                        hexChars[x++] = '\r';
                        hexChars[x++] = '\n';

                       /* String s0 = new String(buffer,0,num);
                        for(i=0;i<num;i++){
                            //System.out.println(Integer.toHexString(buffer[i]));

                            if((buffer[i] == 0x0d)&&(buffer[i+1]==0x0a)){
                                buffer_new[n] = 0x0a;
                                i++;
                            }else{
                                //System.out.println(String.format("-0x%02X",buffer[i]));
                                buffer_new[n] = buffer[i];
                            }
                            n++;
                        }

                        //通过使用指定的 charset 解码指定的 byte 子数组，构造一个新的 String。
                        String  my_utf8 = new String(buffer_new,0,n, "GBK");
                        mBlue_Rx_Buffer+=my_utf8;   //写入接收缓存*/
                        String  my_utf8 = new String(hexChars);
                        mBlue_Rx_Buffer += my_utf8;//
                        if(is.available()==0)break;  //短时间没有数据才跳出进行显示
                    }
                    //发送显示消息，进行显示刷新
                    handler.sendMessage(handler.obtainMessage());
                }catch(IOException e){
                }
            }
        }
    };
    // 歌曲列表选择设备响应函数
    //https://www.cnblogs.com/xiaoming-tech/p/5521991.html
    private AdapterView.OnItemClickListener mMusic_list_ClickListener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {//arg3 表示点的是第几行
            // 得到选中内容
            String sel_music = ((TextView) v).getText().toString();
            long sel_num = arg3 + 1;
            String info = "blu_set_list";//因为0表示返回
            System.out.println(info);
            int n = 0;
            if (info.length() == 0) {
                Toast.makeText(getApplicationContext(), "数据为空", Toast.LENGTH_SHORT).show();
                return;
            }
            try {

                OutputStream os = mBluetoothSocket.getOutputStream();   //蓝牙连接输出流
                byte[] bos = info.toString().getBytes("GBK");//1573读出内容按指定编码排列
                for (int i = 0; i < bos.length; i++) {
                    if (bos[i] == 0x0a) n++;
                }
                byte[] bos_new = new byte[bos.length + n];
                n = 0;
                for (int i = 0; i < bos.length; i++) { //手机中换行为0a,将其改为0d 0a后再发送
                    if (bos[i] == 0x0a) {
                        bos_new[n] = 0x0d;
                        n++;
                        bos_new[n] = 0x0a;
                    } else {
                        bos_new[n] = bos[i];
                    }
                    n++;
                }
                os.write(bos_new);
            } catch (IOException e) {
                Log.d("--------------","send err");
                e.printStackTrace();
            }
        }
    };
    //消息处理队列
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            double df;

            if(uCSB_PAR.data_dis_activity == 1){

                data_dis_activity.tv_in.setText(mBlue_Rx_Buffer);   //显示数据

                if(rx_count_time++>100){
                    mBlue_Rx_Buffer = "";
                    rx_count_time = 0;
                    //data_dis_activity.tv_in.setText("  ");
                }
                //data_dis_activity.scrollView.scrollTo(0, data_dis_activity.tv_in.getMeasuredHeight()); //跳至数据最后一页
            }

            //music_sampleRate_TextView.setText(uCSB_PAR.uiSamplePerSec + "Hz");
            if((uCSB_PAR.update_reg_f&0x02) == 2) {
                uCSB_PAR.update_reg_f -=2;
/*
                df = (float)MainActivity.uCSB_PAR.a_b_dis_bias;config_par_activity.a_b_dis_bias_EditText.setText(String.format("%.3f",df));
                df = (float)MainActivity.uCSB_PAR.a_b_l_par;config_par_activity.a_b_l_par_EditText.setText(String.format("%.3f",df));

                df = (float)MainActivity.uCSB_PAR.a_temp_bias;config_par_activity.a_temp_bias_EditText.setText(String.format("%.3f",df));
                df = (float)MainActivity.uCSB_PAR.b_temp_bias;config_par_activity.b_temp_bias_EditText.setText(String.format("%.3f",df));

                df = (float)MainActivity.uCSB_PAR.a_dis_bias;config_par_activity.a_dis_bias_EditText.setText(String.format("%.3f",df));
                df = (float)MainActivity.uCSB_PAR.b_dis_bias;config_par_activity.b_dis_bias_EditText.setText(String.format("%.3f",df));

                df = (float)MainActivity.uCSB_PAR.AV_k;config_par_activity.AV_k_EditText.setText(String.format("%.3f",df));
                df = (float)MainActivity.uCSB_PAR.section_area;config_par_activity.section_area_EditText.setText(String.format("%.3f",df));
*/
                Intent serveIntent = new Intent(getApplicationContext(), config_par_activity.class); //跳转活动
                startActivityForResult(serveIntent, 1); //设置返回宏定义
            };

            if((uCSB_PAR.update_reg_f&0x01) == 1) {//采集数据显示
                uCSB_PAR.update_reg_f -=1;
                df = (float)uCSB_PAR.ws_0;ws_0_TextView.setText(String.format("%.3f",df));
                df = (float)uCSB_PAR.ws_1;ws_1_TextView.setText(String.format("%.3f",df));

                df = (float)uCSB_PAR.ws_10;ws_10_TextView.setText(String.format("%.3f",df));
                df = (float)uCSB_PAR.ws_30;ws_30_TextView.setText(String.format("%.3f",df));


                df = (float)uCSB_PAR.a_b_dis;a_b_dis_TextView.setText(String.format("%.3f",df));
                df = (float)uCSB_PAR.b_a_dis;b_a_dis_TextView.setText(String.format("%.3f",df));

                df = (float)uCSB_PAR.a_temp;a_temp_TextView.setText(String.format("%.3f",df));
                df = (float)uCSB_PAR.b_temp;b_temp_TextView.setText(String.format("%.3f",df));

                a_b_tof_TextView.setText(Float.toString( uCSB_PAR.a_ft));
                b_a_tof_TextView.setText(Float.toString(uCSB_PAR.b_ft));

                a_res_value_TextView.setText(Float.toString(uCSB_PAR.a_res));
                b_res_value_TextView.setText(Float.toString(uCSB_PAR.b_res));

                if(uCSB_PAR.wd_0 == 0){
                    wd_0_TextView.setText("A->B");
                }else{
                    wd_0_TextView.setText("B->A");
                }

                if(uCSB_PAR.wd_1 == 0){
                    wd_1_TextView.setText("A->B");
                }else{
                    wd_1_TextView.setText("B->A");
                }

                if(uCSB_PAR.wd_10 == 0){
                    wd_10_TextView.setText("A->B");
                }else{
                    wd_10_TextView.setText("B->A");
                }

                if(uCSB_PAR.wd_30 == 0){
                    wd_30_TextView.setText("A->B");
                }else{
                    wd_30_TextView.setText("B->A");
                }

            };

        }
    };
    //消息处理队列
    final Handler seekbar_handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(uCSB_PAR.startstop_f == 1){
                //send ff 03 41 1f 00 10 74 22
                //ret  FF 03 20 40 9F AE 14 40 9C CC CC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3F 80 00 00 45 BE
                byte[] bArray = new byte[8];
                bArray[0] = (byte)0xff;
                bArray[1] = (byte)modbus_read;
                bArray[2] = 0x41;
                bArray[3] = 0x00;
                bArray[4] = 0x00;
                bArray[5] = 31;//size 31*2=62
                bArray[6] = (byte)0x05;
                bArray[7] = (byte)0xe0;
                blu_send_hex(bArray);
            }
        }
    };

    //关闭程序掉用处理部分
    public void onDestroy(){
        super.onDestroy();
        if(mBluetoothSocket!=null)  //关闭连接socket
            try{
                mBluetoothSocket.close();
            }catch(IOException e){}
        	//mBluetoothSocket.close();  //关闭蓝牙服务
    }
}
